<template>
  <div class="creat-drawer-box">
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="140px"
      :label-position="'left'"
      :validate-on-rule-change="false"
      @validate="validate"
    >
      <el-form-item :label="$t('COMMON_NAME')" class="formVolumeName" prop="volumeName">
        <el-tooltip
          v-model:visible="popoverVisible.volumeName"
          popper-class="no-wrap-popover"
          placement="bottom"
          :teleported="false"
          trigger-keys
        >
          <template #content>
            <span id="volumeNameInputTip">{{ traduction('STORE_ASSIC15',{param: nameMaxlength}) }}</span>
          </template>
          <el-input
            v-model="form.volumeName"
            v-addId.input="'volumeName'"
            :disabled="isPMCCard && form.checkedLeveTwo"
            :maxlength="nameMaxlength"
            @focus="focus('volumeName')"
            @blur="blur('volumeName')"
            @clear="clear('volumeName')"
            @input="input('volumeName', $event)"
          >
            <template #suffix>
              <ErrorIcon />
              <ClearableIcon />
            </template>
          </el-input>
        </el-tooltip>
        <el-tooltip 
          placement="bottom" 
          :teleported="false" 
          trigger-keys
          v-if="!isAriesCard && !isSmartHBA && supportCacheCade"
        >
          <template #content>
            <span id="twoCacheTip">{{ traduction('STORE_LEVEL_TWO_CACHE_TIP') }}</span>
          </template>
          <el-checkbox
            :id="'twoCache'"
            v-model="form.checkedLeveTwo"
            :label="$t('STORE_LEVEL_TWO_CACHE')"
            @change="twoCacheChecked"
          />
        </el-tooltip>
      </el-form-item>
      <el-form-item :label="$t('STORE_STRIPE_SIZE')" v-if="!isPMCCard || !isTwoCache">
        <el-select
          v-model="form.storeStripeSize"
          v-addId.select="'stripeSize'"
          :disabled="form.storeStripeSizeDisabled"
          :suffix-icon="PullDownTriangle"
          :placeholder="form.storeStripeSize"
          @change="selectCahnge($event, 'optimumIOSizeBytes')"
        >
          <el-option
            v-for="item in form.storeStripeSizeOption"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('STORE_CACHE_LINE')" v-if="!isPMCCard || isTwoCache">
        <el-select
          v-model="form.cacheLineSize.value"
          v-addId.select="'CacheLineSize'"
          :disabled="form.cacheLineSizeDisabled"
          :suffix-icon="PullDownTriangle"
          :placeholder="form.cacheLineSize.value"
          @change="selectCahnge($event, 'cacheLineSize')"
        >
          <el-option
            v-for="item in form.cacheLineSizeOptions"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('STORE_READ_POLICY')" v-if="!isPMCCard">
        <el-select
          v-model="form.storeReadPolicy"
          v-addId.select="'readPolicy'"
          :disabled="form.storeReadPolicyDisabled"
          :placeholder="form.storeReadPolicy"
          :suffix-icon="PullDownTriangle"
          @change="selectCahnge($event, 'defaultReadPolicy')"
        >
          <el-option
            v-for="item in form.storeReadPolicyOption"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('STORE_WRITE_POLICY')" v-if="!isPMCCard || isTwoCache">
        <el-select
          v-model="form.storeWritePolicy"
          v-addId.select="'writePolicy'"
          :disabled="form.storeWritePolicyDisabled"
          :suffix-icon="PullDownTriangle"
          :placeholder="form.storeWritePolicy"
          @change="selectCahnge($event, 'defaultWritePolicy')"
        >
          <el-option
            v-for="item in form.storeWritePolicyOption"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="!isPMCCard && !isAriesCard" :label="$t('STORE_IO_POLICY')">
        <el-select
          v-model="form.storeIOPolicy"
          v-addId.select="'ioPolicy'"
          :disabled="form.storeIOPolicyDisabled"
          :suffix-icon="PullDownTriangle"
          :placeholder="form.storeIOPolicy"
          @change="selectCahnge($event, 'defaultCachePolicy')"
        >
          <el-option
            v-for="item in form.storeIOPolicyOption"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('STORE_CACHE_POLICY')" v-if="!isPMCCard">
        <el-select
          v-model="form.storeCachePolicy"
          v-addId.select="'driverCachePolicy'"
          :disabled="form.storeCachePolicyDisabled"
          :suffix-icon="PullDownTriangle"
          :placeholder="form.storeCachePolicy"
          @change="selectCahnge($event, 'driveCachePolicy')"
        >
          <el-option
            v-for="item in form.storeCachePolicyOption"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="!isPMCCard && !isAriesCard" :label="$t('STORE_ACCESS_POLICY')">
        <el-select
          v-model="form.storeAccessPolicy"
          v-addId.select="'accessPolicy'"
          :disabled="form.storeAccessPolicyDisabled"
          :suffix-icon="PullDownTriangle"
          :placeholder="form.storeAccessPolicy"
          @change="selectCahnge($event, 'accessPolicy')"
        >
          <el-option
            v-for="item in form.storeAccessPolicyOption"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="(!isTwoCache && isPMCCard) || !isPMCCard" :label="$t('STORE_INITITYPE')">
        <el-select
          v-model="form.storeInititype"
          v-addId.select="'initMode'"
          :disabled="form.storeInititypeDisabled"
          :suffix-icon="PullDownTriangle"
          :placeholder="form.storeInititype"
          @change="selectCahnge($event, 'initializationMode')"
        >
          <el-option
            v-for="item in form.storeInititypeOption"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('STORE_RAI_LEVEL')" class="required-form-item">
        <el-select
          v-model="form.storeRaiLevel"
          v-addId.select="'raidLevel'"
          :disabled="form.storeRaiLevelDisabled"
          :suffix-icon="PullDownTriangle"
          :placeholder="form.storeRaiLevel"
          @change="selectCahnge($event, 'volumeRaidLevel')"
        >
          <el-option
            v-for="item in form.storeRaiLevelOption"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('STORE_SPAN_NUM')" prop="spanNum">
        <el-input
          :id="'spanNum'"
          v-model="form.spanNum"
          :disabled="form.spanNumDisabled"
          @change="spanChange"
          @focus="isUserInput(true)"
          @blur="isUserInput(false)"
        ></el-input>
      </el-form-item>
      <el-form-item
        :label="$t('HOME_PHYSICAL_DISK')"
        class="required-form-item"
        :class="{ 'text-el-form-item': form.physicalDiskList.length === 0 }"
      >
        <div v-show="form.physicalDiskList.length > 0" id="physicalDisk">
          <el-checkbox-group v-model="form.physicalCheckList">
            <el-checkbox
              v-for="item in form.physicalDiskList"
              :id="item.getName"
              :key="item.getName"
              :label="item.getName"
              :disabled="item.getDisable"
              @change="changeCheckState(item).option"
            />
          </el-checkbox-group>
        </div>
        <div v-show="form.physicalDiskList.length === 0" id="physicalDisk">
          <span class="ti3-icon ti3-icon-staricon redStar">{{ traduction('STORE_NO_DRIVE') }}</span>
        </div>
      </el-form-item>
      <el-form-item
        v-show="form.acailableCapacityList.length > 0"
        :label="$t('STORE_AVAILABLE_CAPACITY')"
      >
        <div id="availavleCapacity">
          <el-radio-group
            v-model="form.availableSelect"
            @change="availableChange(volumeMembers.availableSelect)"
          >
            <el-radio v-for="item in form.acailableCapacityList" :key="item" :label="item.getValue">
              {{ item.getLabel }}
            </el-radio>
          </el-radio-group>
        </div>
      </el-form-item>
      <el-form-item :label="$t('COMMON_CAPACITY')" class="formCapacity">
        <el-input
          v-model="form.capacity"
          v-addId.input="'capacity'"
          class="capacity"
          :disabled="form.checkedLeveTwo"
          type="number"
          @input="changeCapacity"
          title=""
        ></el-input>
        <el-select
          v-model="form.capacityUnit"
          v-addId.select="'capacityUnit'"
          :disabled="form.checkedLeveTwo"
          :suffix-icon="PullDownTriangle"
          :placeholder="form.capacityUnit"
          @change="changeUnit"
        >
          <el-option
            v-for="item in form.capacityUnitOptions"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- 加速方法 -->
      <el-form-item :label="$t('STORE_ACCELERATION')" v-if="isPMCCard && !isTwoCache">
        <el-select
          v-model="form.accelerationMethod.value"
          v-addId.select="'accelerationMethod'"
          :disabled="isMaxCacheMethod"
          :suffix-icon="PullDownTriangle"
          @change="editChange('accelerationMethod')"
          class="tiSelect"
        >
          <el-option
            v-for="item in form.accelerationMethod.options"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- 关联逻辑盘 -->
      <el-form-item :label="$t('STORE_ASSOCIATE_LOGIC')" v-if="isPMCCard && isTwoCache">
        <el-select
          v-model="form.associationLogical"
          v-addId.select="'associationLogical'"
          :disabled="associationLogicalDisabled"
          :suffix-icon="PullDownTriangle"
          @change="editChange('associationLogical')"
          class="tiSelect"
        >
          <el-option
            v-for="item in form.associationLogicalOptions"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div class="footer">
      <el-button type="primary" :disabled="buttonState" @click="onSubmit">
        {{ $t('COMMON_SAVE') }}
      </el-button>
      <el-button @click="cancel">{{ $t('COMMON_CANCEL') }}</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { nextTick, onMounted, reactive, ref, watch } from 'vue';
import useStore from '@/stores';
import { BaseValidators } from '@/validators/base-validators';
import { traduction } from '@/utils/language';
import { VALID_PRODUCT_POSITION } from '@/utils/regular';
import {
  VolumeMembersModel,
  VolumePolicyModel,
  RaidNode,
  StorageTree,
  Raid,
  RaidType,
  VolumeCreateModel,
  IOptions,
  AvailableCapacity,
} from '../../models';
import { factory } from '../raid/raid.service';
import {
  capacityChange,
  changeDriveDisable,
  driveAndCapacityCount,
  relateFalse,
  relateTrue,
  spanCount,
  unitChange,
} from './volume-create.utils';
import PullDownTriangle from '@/components/PullDownTriangle/PullDownTriangle.vue';
import ErrorIcon from '@/components/ErrorIcon/ErrorIcon.vue';
import ClearableIcon from '@/components/ClearableIcon/ClearableIcon.vue';
import { loading } from '@/utils/composition';
import { transCapacity, computeCapacity } from '../../utils/storage.utils';
import { rangeVerification } from '@/validators/validation-functions';
import { VolumeCreateService } from '../../components/volume-create/volume-creat.servics';

const emit = defineEmits(['handleClose']);
const store = useStore();
const volumeCreateService = new VolumeCreateService();
const popoverVisible = reactive({
  volumeName: false,
});
const isTwoCache: any = ref(false);
const formRef = ref();
const saveBtnState = ref(false);
const props = defineProps({
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
});
const param = {};
const buttonState = ref(true);
let userInput = false;
let volumeCreate = VolumeCreateModel.getInstance();
let isPMCCard: boolean = false;
let isAriesCard: boolean = false;
let isSpecials8iBoard: boolean = false;
let nameMaxlength: number = 15;
const isSmartHBA = ref(false);
const supportCacheCade = ref(false);
let avaliableLogicals: IOptions[];
const temData = {
  volumeName: '',
  checkedLeveTwo: false,
  storeStripeSize: '64KB',
  storeStripeSizeDisabled: false,
  storeReadPolicy: 'Read Ahead',
  storeReadPolicyDisabled: true,
  storeWritePolicy: 'Write Through',
  storeWritePolicyDisabled: true,
  storeIOPolicy: 'Cached IO',
  storeIOPolicyDisabled: true,
  storeCachePolicy: 'Disk\'s Default',
  storeCachePolicyDisabled: false,
  storeAccessPolicy: 'Read Write',
  storeAccessPolicyDisabled: false,
  storeInititype: 'No Init',
  storeInititypeDisabled: false,
  storeRaiLevel: '0',
  storeRaiLevelDisabled: false,
  spanNum: '',
  spanNumDisabled: true,
  physicalDisk: '',
  physicalDiskList: [],
  acailableCapacity: '',
  capacity: '',
  capacityUnit: 'MB',
};
interface CreatType {
  volumeName: string | null;
  [propName: string]: any;
}

// 表单数据声明
const form: CreatType = reactive({
  volumeName: '',
  checkedLeveTwo: false,
  storeStripeSize: '64KB',
  storeStripeSizeDisabled: false,
  storeStripeSizeOption: [
    {
      value: '64KB',
      label: '64KB',
    },
  ],
  storeReadPolicy: 'Read Ahead',
  storeReadPolicyDisabled: true,
  storeReadPolicyOption: [
    {
      value: 'Read Ahead',
      label: 'Read Ahead',
    },
  ],
  storeWritePolicy: 'Write Through',
  storeWritePolicyDisabled: true,
  storeWritePolicyOption: [
    {
      value: 'Write Through',
      label: 'Write Through',
    },
  ],
  storeIOPolicy: 'Cached IO',
  storeIOPolicyDisabled: true,
  storeIOPolicyOption: [
    {
      value: 'Cached IO',
      label: 'Cached IO',
    },
  ],
  storeCachePolicy: 'Disk\'s Default',
  storeCachePolicyDisabled: false,
  storeCachePolicyOption: [
    {
      value: 'Disk\'s Default',
      label: 'Disk\'s Default',
    },
  ],
  storeAccessPolicy: 'Read Write',
  storeAccessPolicyDisabled: false,
  storeAccessPolicyOption: [
    {
      value: 'Read Write',
      label: 'Read Write',
    },
  ],
  storeInititype: 'No Init',
  storeInititypeDisabled: false,
  storeInititypeOption: [
    {
      value: 'No Init',
      label: 'No Init',
    },
  ],
  storeRaiLevel: '0',
  storeRaiLevelDisabled: false,
  storeRaiLevelOption: [
    {
      value: '0',
      label: '0',
    },
  ],
  // 每个span的成员盘数
  spanNum: '',
  // 每个span的成员盘数可用状态
  spanNumDisabled: true,
  physicalDisk: '',
  physicalDiskList: [],
  physicalCheckList: [],
  acailableCapacity: '',
  acailableCapacityList: [],
  capacity: '',
  capacityUnit: 'MB',
  capacityUnitOptions: [
    {
      value: 'MB',
      label: 'MB',
    },
  ],
  cacheLineSize: {
    value: '',
    option: [{ id: '', label: '', name: '' }],
    disable: false,
  },
  cacheLineSizeDisabled: false,
  cacheLineSizeOptions: [],
  associationLogical: '',
  associationLogicalDisabled: false,
  associationLogicalOptions: [],
  accelerationMethod: {
    value: '',
    option: [{ id: '', label: '', name: '' }],
    disable: false,
  },
});
const rules = reactive({
  volumeName: {
    trigger: 'change',
    type: 'text',
    min: 1,
    max: 15,
    message: traduction('VALIDTOR_FORMAT_ERROR'),
    validator: (rule: any, val: string, callback: any): void | boolean => {
      const { message } = rule;
      if (!VALID_PRODUCT_POSITION.test(val)) {
        callback(new Error(message));
        return false;
      }
      return true;
    },
  },
  spanNum: {
    trigger: 'change',
    type: 'number',
    isInteger: true,
    min: 1,
    max: 32,
    message: traduction('STORE_INTEGER3TO32'),
    validator: rangeVerification,
  },
});
function onSubmit() {
  emit('handleClose', true, param);
}
function cancel() {
  emit('handleClose', false);
}
// 表单校验结果
const validateResult = {};
// 表单校验发生时 - 控制保存按钮状态 state:校验结果
function validate(key: string, state: boolean) {
  validateResult[key] = state;
  nextTick(() => {
    setSaveBtnState();
  });
}

function focus(key: string) {
  popoverVisible[key] = true;
}

function blur(key: string) {
  popoverVisible[key] = false;
}

function clear(key: string) {
  // 如果没有focus，那么这个地方需要手动调用一次校验
  if (!popoverVisible[key]) {
    formRef.value.validateField(key);
  }
}
function input(key: string, val: string) {
  validateResult[key] = rules[key].validator(rules[key], val, () => {});
  VolumePolicyModel.getInstance().selectData.name = val;
  nextTick(() => {
    setSaveBtnState();
  });
}
// 设置保存按钮状态
function setSaveBtnState() {
  for (let key in validateResult) {
    // 任意一个校验失败
    if (validateResult[key] === false) {
      saveBtnState.value = false;
      return;
    }
  }
}
let volumePolicy: VolumePolicyModel;
let volumeMembers: VolumeMembersModel;
let raidNode: any;
function twoCacheChecked(state: boolean) {
  if (isPMCCard) {
    setCheckBoxItem();
    VolumePolicyModel.initInstance(
      raidNode.getRaid.getChidrenData.maxSize,
      raidNode.getRaid.getChidrenData.minSize,
      !raidNode.getRaid.getChidrenData.readPolicyConfig,
      !raidNode.getRaid.getChidrenData.writePolicyConfig,
      !raidNode.getRaid.getChidrenData.IOPolicyConfig,
      !raidNode.getRaid.getChidrenData.drivePolicyConfig,
      !raidNode.getRaid.getChidrenData.accessPolicyConfig,
      false,  
      state,
      raidNode.getRaidType,
      avaliableLogicals,
    );
  } else {
    VolumePolicyModel.initInstance(
      raidNode.getRaid.getChidrenData.maxSize,
      raidNode.getRaid.getChidrenData.minSize,
      !raidNode.getRaid.getChidrenData.readPolicyConfig,
      !raidNode.getRaid.getChidrenData.writePolicyConfig,
      !raidNode.getRaid.getChidrenData.IOPolicyConfig,
      !raidNode.getRaid.getChidrenData.drivePolicyConfig,
      !raidNode.getRaid.getChidrenData.accessPolicyConfig,
      false,
      state,
      raidNode.getRaidType,
    );
  }

  const raidLevel = raidNode.getRaid.getRAIDLevels;
  VolumeMembersModel.initInstance(
    {
      disable: false,
      levels: raidLevel ? (raidLevel.value as []) : [],
      towState: state,
      specials8iBoard: raidNode.getSpecials8iBoard || false,
      raidType: raidNode.getRaidType || '',
    },
    raidNode.getRaid.getDriveArr,
  );
  volumePolicy = VolumePolicyModel.getInstance();
  isTwoCache.value = volumePolicy.getTwoCache;
  initForm();
}

function setCheckBoxItem(state: boolean = false) {
  if (!isPMCCard) {return; }
  raidNode.getRaid.getDriveArr.forEach((item: any) => {
    item.checkDisableState(false);
    item.setOpoInitState = false;
    item.setCheckedAllClear = false;
    if (item.getMediaType === 'HDD' && state) {
      item.setOpoInitState = state;
      item.setDisable = item.getIsDisable ? item.getIsDisable : state;
    }
  });
}
onMounted(() => {
  const selectNode = StorageTree.getInstance().getCheckedNode as any;
  let getRaidPost;
  loading(true);
  factory(selectNode, selectNode.getUrl)
    .then((raid: any) => {
      selectNode.setRaid = raid;
      getRaidPost = selectNode;
      raidNode = selectNode;
      initFormPolicy(getRaidPost);
      initFormMembers(getRaidPost);
      getDefult(form);
      volumeCreate = VolumeCreateModel.getInstance();
      initForm();
      loading(false);
    })
    .catch(() => {
      loading(false);
    });
});

function initFormMembers(raidNodeData: RaidNode) {
  const raidLevel = raidNodeData.getRaid.getRAIDLevels;
  VolumeMembersModel.initInstance(
    {
      disable: false,
      levels: raidLevel ? (raidLevel.value as []) : [],
      towState: false,
      specials8iBoard: raidNodeData.getSpecials8iBoard || false,
      raidType: raidNodeData.getRaidType || '',
    },
    raidNodeData.getRaid.getDriveArr,
  );
  // 获取raid类型：PMC卡、9560-8i和9560-16i两种类型的板卡、1880卡
  if (raidNodeData.getRaidType === RaidType.PMC || raidNodeData.getRaidType === RaidType.HBA) {
    isPMCCard = true;
  } else if (raidNodeData.getRaidType === RaidType.ARIES) {
    isAriesCard = true;
  } else {}
  isSpecials8iBoard = raidNodeData.getSpecials8iBoard;
  driveAndCapacityCount();
  volumeMembers = VolumeMembersModel.getInstance();
}
function initFormPolicy(raidNodeData: RaidNode) {
  avaliableLogicals = volumeCreateService.getLogicList();
  supportCacheCade.value = raidNode.getSupportCacheCade;
  if (raidNodeData.getRaidType === RaidType.PMC || raidNodeData.getRaidType === RaidType.HBA) {
    if (raidNode.getRaidType === RaidType.HBA) {
      isSmartHBA.value = true;
    } else {
      isSmartHBA.value = false;
    }
    isPMCCard = true;
    // PMC卡支持64位字符
    nameMaxlength = 64;
    VolumePolicyModel.initInstance(
      raidNode.getRaid.getChidrenData.maxSize,
      raidNode.getRaid.getChidrenData.minSize,
      true,
      true,
      true,
      true,
      true,
      false,
      false,
      raidNodeData.getRaidType,
    );
  } else {
    if (raidNodeData.getRaidType === RaidType.ARIES) {    
      isAriesCard = true;
      // 1880卡 支持23位字符
      nameMaxlength = 20;
    }
    VolumePolicyModel.initInstance(
      raidNodeData.getRaid.getChidrenData.maxSize,
      raidNodeData.getRaid.getChidrenData.minSize,
      !raidNodeData.getRaid.getChidrenData.readPolicyConfig,
      !raidNodeData.getRaid.getChidrenData.writePolicyConfig,
      !raidNodeData.getRaid.getChidrenData.IOPolicyConfig,
      !raidNodeData.getRaid.getChidrenData.drivePolicyConfig,
      !raidNodeData.getRaid.getChidrenData.accessPolicyConfig,
      false,
      false,
      raidNodeData.getRaidType,
    );
  }
  volumePolicy = VolumePolicyModel.getInstance();
  isTwoCache.value = volumePolicy.getTwoCache;
}
function getDefult(forms: any) {
  for (const key in forms) {
    if (Object.prototype.hasOwnProperty.call(forms, key)) {
      temData[key] = forms[key];
    }
  }
}
function initForm() {
  form.volumeName = volumePolicy.selectData.name;
  form.checkedLeveTwo = volumePolicy.selectData.createCacheCadeFlag;
  form.storeStripeSize = volumePolicy.selectData.optimumIOSizeBytes?.id;
  form.storeStripeSizeDisabled = volumePolicy.getStripeSize.disable;
  form.storeStripeSizeOption = [...volumePolicy.getStripeSize.options];
  form.storeReadPolicy = volumePolicy.selectData.defaultReadPolicy?.id;
  form.storeReadPolicyDisabled = volumePolicy.getReadPolicy.disable;
  form.storeReadPolicyOption = [...volumePolicy.getReadPolicy.options];
  form.storeWritePolicy = volumePolicy.selectData.defaultWritePolicy?.id;
  form.storeWritePolicyDisabled = volumePolicy.getWritePolicy.disable;
  form.storeWritePolicyOption = [...volumePolicy.getWritePolicy.options];
  form.storeIOPolicy = volumePolicy.selectData.defaultCachePolicy?.id;
  form.storeIOPolicyDisabled = volumePolicy.getIOPolicy.disable;
  form.storeIOPolicyOption = [...volumePolicy.getIOPolicy.options];
  form.storeCachePolicy = volumePolicy.selectData.driveCachePolicy?.id;
  form.storeCachePolicyDisabled = volumePolicy.getDriverCachePolicy.disable;
  form.storeCachePolicyOption = [...volumePolicy.getDriverCachePolicy.options];
  form.storeAccessPolicy = volumePolicy.selectData.accessPolicy?.id;
  form.storeAccessPolicyDisabled = volumePolicy.getAccessPolicy.disable;
  form.storeAccessPolicyOption = [...volumePolicy.getAccessPolicy.options];
  form.storeInititype = volumePolicy.selectData.initializationMode?.id;
  form.storeInititypeDisabled = volumePolicy.getInitMode.disable;
  form.storeInititypeOption = volumePolicy.getInitModeOptions(raidNode?.getRaidType);
  form.storeRaiLevel = volumeMembers.getSelectData.volumeRaidLevel?.id;
  form.storeRaiLevelDisabled = volumeMembers.getRaidLevel.disable;
  form.storeRaiLevelOption = [...volumeMembers.getRaidLevel.options];
  form.capacityUnitOptions = [...volumeMembers.getCapacity.options];
  form.accelerationMethod.value = volumePolicy.selectData.accelerationMethod;
  form.accelerationMethod.options = volumePolicy.getInitPmcOptions(raidNode?.getRaidType);
  form.accelerationMethod.disable = volumePolicy.getAccelerationMethod.disable;
  form.associationLogical = volumePolicy.selectData.associationLogical;
  form.associationLogicalOptions = volumePolicy.getAssociationLogical.options;
  form.associationLogicalDisabled = volumePolicy.getAssociationLogical.disable;
  if (volumePolicy.selectData.cacheLineSize !== null) {
    form.cacheLineSize = volumePolicy.selectData.cacheLineSize;
  }
  form.cacheLineSizeOptions = volumePolicy.getCacheLineSize.options;
  form.cacheLineSizeDisabled = volumePolicy.getCacheLineSize.disable;

  initDisk();
}
function selectCahnge(val: string, key: string) {
  volumePolicy.selectData[key] = { id: val, label: '', name: 'IOptions' };
  if (key === 'volumeRaidLevel') {
    raidLevelChange({ id: val, label: val.replace('RAID', ''), name: 'IOptions' });
  }
  setSaveBtnState();
}
function changeCheckState(check: any) {
  const option = (state: boolean) => {
    const checkDrive: any = volumeMembers.getCheckArr.find((item: any) => {
      return item.driveId === check.driveId;
    });
    // 更改物理盘的选中状态
    checkDrive.setChecked = state;
    const raidLevels = raidNode.getRaid.getRAIDLevels;
    const raidLevelList = <any>[];
    if (raidLevels.value instanceof Array) {
      raidLevels.value.forEach((item: any) => {
        raidLevelList.push(item);
      })
    }
    const raidLevelOption = {
      relatedDriveNum: null,
      raidLevelList: raidLevelList,
    };
    // 如果选中的物理盘拥有关联对象
    if (checkDrive.getRelated.length > 0) {
      if (state) {
        if (isPMCCard) {
          volumeMembers.isHaveRelated = true;
          volumeMembers.createRelated = true;
          // 盘容量未用完的物理盘为一个盘组，一个勾选本组均勾选，且级别、每个span的成员盘数继承之前的逻辑盘
          const raidLevel = checkDrive.getRaidLevel;
          if (!String(raidLevel.id).includes('RAID')) {
            raidLevel.id = `RAID${raidLevel.id}`;
          }
          volumeMembers.setRAIDLevelSelect = raidLevel;
          volumeMembers.setSpanNum = checkDrive.getSpanNum;
          form.spanNumDisabled = false;
          // 新增可用容量
          volumeMembers.addAvailableCapacity(new AvailableCapacity(checkDrive.getAvailableCapacity[0]));
          const checkedDrivesList = <any>[];
          volumeMembers.getCheckArr.forEach(item => {
            if (item.checked) {
              checkedDrivesList.push(item.getID);
            }
          });
          volumeMembers.getSelectData.drives = checkedDrivesList;
          raidLevelOption.relatedDriveNum = checkedDrivesList.length;
          volumeMembers.setRAIDLevelOptions = raidLevelOption;
          paramChanged();
          // 更改span成员数校验范围和校验提示词
          form.spanNum = volumeMembers.getSpanNum.value;
        } else {
          relateTrue(checkDrive);
          // 物理盘缓存策略的值设置为已选物理盘对应的缓存策略值
          const driveCachePolicy = VolumePolicyModel.getInstance().getDriverCachePolicy.options.filter(item => 
            item.id === checkDrive?.getDiskCachePolicy);
          volumePolicy.selectData.driveCachePolicy = driveCachePolicy[0];
          if (isAriesCard) {
            volumePolicy.setDriverCachePolicy = true;
          }
          // 更改span成员数校验范围和校验提示词
          form.spanNum = volumeMembers.getSpanNum.value;
          form.spanNumDisabled = true;
        }
      } else {
        relateFalse();
        volumePolicy.selectData.driveCachePolicy = VolumePolicyModel.getInstance().getDriverCachePolicy.options[0];
        if (isAriesCard) {
          // 取消物理盘缓存策略置灰，置为初始值
          volumePolicy.setDriverCachePolicy = false;
        }
        // 重置raid级别可选项
        volumeMembers.setRAIDLevelOptions = raidLevelOption;
        // 更改span成员数校验范围和校验提示词
        form.spanNum = null;
        setSpanValid(volumeMembers.getSpanNum);
        // 子组盘不可用
        form.spanNumDisabled = true;
      }
    } else {
      driveAndCapacityCount();
      spanCount();
      if (volumePolicy.getTwoCache) {
        // 创建maxCache逻辑盘容量处理
        setMaxCacheCapacity(true);
      }
      diskMixedGroup();
    }
    if (volumeMembers.getSelectData.drives?.length === 0) {      
      // 如果没有选中项，放开所有物理盘
      changeDriveDisable(false);
    }
    initDisk();
    checkBtnState();
  };
  return { option };
}

// 修改Raid级别、子组成员盘数及物理盘导致的参数变化
function paramChanged() {
  const drives = volumeMembers.getSelectData.drives as number[];
  const spanNumber = volumeMembers.getSelectData.spanNumber as number;
  const volumeRaidLevel = volumeMembers.getSelectData.volumeRaidLevel;
  const capacityMBytes = volumeMembers.getCheckArr.filter(item => item.getID === drives[0])[0].getTotalFreeSpaceMiB;
  if (volumeRaidLevel?.label === '50') {
    volumeMembers.setSpanNumDisable = false;
    if (spanNumber < 3 || spanNumber > volumeMembers?.getSelectData?.drives.length / 2) {
      return;
    }
  } else if (volumeRaidLevel?.label === '60') {
    volumeMembers.setSpanNumDisable = false;
    if (spanNumber < 4 || spanNumber > volumeMembers?.getSelectData?.drives.length / 2) {
      return;
    }
  } else {
    volumeMembers.setSpanNumDisable = true;
    form.spanNum = null;
    form.spanNumDisabled = true;
  }
  let availableBate = 0;
  switch(volumeRaidLevel?.label) {
    case '1': case '10':
      availableBate = capacityMBytes / 2;
      break;
    case '1(ADM)': case '10(ADM)': case '1Triple': case '10Triple':
      availableBate = capacityMBytes / 3;
      break;
    case '5':
      availableBate = capacityMBytes * (drives.length - 1) / drives.length;
      break;
    case '6':
      availableBate = capacityMBytes * (drives.length - 2) / drives.length;
      break;
    case '50':
      availableBate = capacityMBytes * (drives.length - drives.length / spanNumber) / drives.length;
      break;
    case '60':
      availableBate = capacityMBytes * (drives.length - 2 * drives.length / spanNumber) / drives.length;
      break;
    default:
      availableBate = capacityMBytes;
      break;
  }
  volumeMembers.setAvailableCapacity = [new AvailableCapacity(availableBate)];
  // 容量初始化--可用容量的选中项
  volumeMembers.setCapacityObj = {
    value: volumeMembers.availableSelect?.getValue || null,
    unit: volumeMembers.availableSelect.getUnit,
    options: volumeMembers.getCapacity.options,
    batyValue: volumeMembers.availableSelect?.getBatyValue || null,
    oldValue: volumeMembers.availableSelect?.getBatyValue || null,
  };
  volumeMembers.checkSave();
}

// 初始化raid级别、子组成员盘物理盘和容量参数
function initDisk(): void {
  form.physicalDiskList = volumeMembers.getCheckArr;
  form.physicalCheckList = volumeMembers.getCheckArr
    .filter(item => {
      return item.checked;
    })
    .map(item => {
      return item.getName;
    });
  form.capacity = volumeMembers.getCapacity.value;
  form.capacityUnit = volumeMembers.getCapacity.unit.id;
  form.storeRaiLevel = volumeMembers.getSelectData.volumeRaidLevel?.id;
  form.storeRaiLevelDisabled = volumeMembers.getRaidLevel.disable;
  form.acailableCapacityList.splice(0);
  form.acailableCapacityList.push(...volumeMembers.getAvailableCapacity);
  form.availableSelect = volumeMembers.availableSelect?.getValue;
}

function diskMixedGroup() {
  const checkedDisk = volumeMembers.getCheckArr.filter(item => item.checked);
  if (checkedDisk.length === 0) {
    return;
  }
  volumeMembers.getCheckArr.forEach(item => {
    // 博通卡：当介质类型是SSD时，SAS和SATA不能混组
    const disableRuleBT =
      !isAriesCard && !isPMCCard && checkedDisk[0].getMediaType === 'SSD' && item.getProtocol !== checkedDisk[0].getProtocol;
    // pmc卡：SAS和SATA不能混组
    const disableRulePmc = isPMCCard && (item.getProtocol !== checkedDisk[0].getProtocol);
    // 普通盘和SSD盘不能混组
    const disableRuleType = item.getMediaType !== checkedDisk[0].getMediaType;
    if (disableRuleBT || disableRulePmc || disableRuleType) {
      item.setDisable = true;
    }
  });
}

/**
 * 用户手动更改容量触发方法
 * @param capacity 用户输入的容量
 */
function changeCapacity(capacity: number) {
  if ((capacity !== 0 && !capacity) || capacity < 0) {
    volumeMembers.setCapacity = null;
    form.capacity = null;
    if (capacity < 0) {
      volumeMembers.setCapacity = 0;
      form.capacity = 0;
    }
  } else {
    const capacityNum = capacityChange(capacity, String(volumeMembers.getCapacity.unit.id));
    if (capacity > capacityNum) {
      // 输入值大于最大值时，容量使用原始数据，且增加“oldValue”属性使下发参数为null
      volumeMembers.setCapacityObj = {
        value: capacityNum,
        unit: volumeMembers.getCapacity.unit,
        options: volumeMembers.getCapacity.options,
        batyValue: transCapacity(capacityNum, volumeMembers.getCapacity.unit.label),
        oldValue: transCapacity(capacityNum, volumeMembers.getCapacity.unit.label),
      };
    } else {
      volumeMembers.setCapacityObj = {
        value: capacityNum,
        unit: volumeMembers.getCapacity.unit,
        options: volumeMembers.getCapacity.options,
        batyValue: transCapacity(capacityNum, volumeMembers.getCapacity.unit.label),
        oldValue: null,
      };
    }
    if (capacityNum < capacity) {
      form.capacity = capacityNum;
    }
    form.capacityUnit = volumeMembers.getCapacity.unit.id;
  }
  checkBtnState();
}
/**
 * 用户更改容量单位触发方法
 * @param unit 容量单位
 */
function changeUnit(ipt: string) {
  const unit = { id: ipt, label: ipt, name: 'IOptions' };
  volumeMembers.setCapacityObj = {
    value: unitChange(String(unit.id)),
    unit,
    options: volumeMembers.getCapacity.options,
    batyValue: volumeMembers.getCapacity.batyValue,
    oldValue: volumeMembers.getCapacity.batyValue,
  };
  form.capacity = volumeMembers.getCapacity.value;
}
/**
 * 可用容量选中改变
 * @param availableSelect 用户选中的可用容量
 */
function availableChange(availableSelect: any) {
  volumeMembers.setCapacityObj = {
    value: availableSelect.getValue,
    unit: availableSelect.getUnit,
    options: volumeMembers.getCapacity.options,
    batyValue: availableSelect.getBatyValue,
    oldValue: null,
  };
}
function checkBtnState() {
  volumeCreate = VolumeCreateModel.getInstance();
  volumeCreate.checkBtnState();
  const memberState = VolumeMembersModel.getInstance().checkSave();
  if (memberState) {
    buttonState.value = true;
  } else {
    buttonState.value = false;
  }
}

/**
 * raid级别与每个span的成员盘数联动
 * @param raidLevel raid级别
 */
function raidLevelChange(raidLevel: any) {
  formRef.value.clearValidate('spanNum');
  volumeMembers.setRAIDLevelSelect = raidLevel;
  // 清空物理盘选中项和容量
  const raidType = isAriesCard ? RaidType.ARIES : null;
  volumeMembers.addCheckArr(volumeMembers.getCheckArr, volumePolicy.getTwoCache as boolean, raidType as string);
  volumeMembers.setCapacity = null;
  changeDriveDisable(false);
  form.spanNum = volumeMembers.getSpanNum.value;
  // 是否使用剩余容量创建逻辑盘，是否是特殊类型raid卡
  spanChangeWithRaidInfo(volumeMembers.createRelated, raidLevel);
  form.capacity = volumeMembers.getCapacity.value;
  form.capacityUnit = volumeMembers.getCapacity.unit.id;
  form.capacityUnitOptions = volumeMembers.getCapacity.options;
  form.physicalCheckList = volumeMembers.getCheckArr
    .filter(item => {
      return item.checked;
    })
    .map(item => {
      return item.getName;
    });
}

/**
 * raid级别与span成员盘数联动（涉及是否使用剩余容量创建逻辑盘、raid卡类型）
 * @param createRelated 是否使用剩余容量创建逻辑盘（true：是，false：否）
 * @param raidLevel raid级别信息
 */
function spanChangeWithRaidInfo(createRelated: boolean, raidLevel: any) {
  if (createRelated) {
    if (raidLevel.id === 'RAID50') {
      form.spanNumDisabled = false;
      form.spanNum = 3;
      rules['spanNum'].min = 3;
    } else if (raidLevel.id === 'RAID60') {
      form.spanNumDisabled = false;
      form.spanNum = 4;
      rules['spanNum'].min = 4;
    } else {
      form.spanNumDisabled = true;
      rules['spanNum'].min = 1;
    }
    // 不使用剩余容量创建逻辑盘
  } else {
    if (raidLevel.id === 'RAID50') {
      form.spanNumDisabled = false;
      form.spanNum = 3;
      rules['spanNum'].min = 3;
      rules['spanNum'].message = traduction('STORE_INTEGER3TO32');
    } else if (raidLevel.id === 'RAID60') {
      form.spanNumDisabled = false;
      // （PMC卡，9560-8i和9560-16i两种类型的板卡，1880卡）raid级别为60，成员盘数量最小数量默认为4，其他情况成员盘为3
      const minValue = isPMCCard || isSpecials8iBoard || isAriesCard ? 4 : 3;
      form.spanNum = minValue;
      rules['spanNum'].min = minValue;
      rules['spanNum'].message =
        minValue === 4 ? traduction('STORE_INTEGER4TO32') : traduction('STORE_INTEGER3TO32');
    } else {
      form.spanNumDisabled = true;
      rules['spanNum'].min = 1;
    }
  }
  volumeMembers.setSpanNum = form.spanNum;
}
function isUserInput(user: boolean) {
  userInput = user;
}
function spanChange() {
  volumeMembers.setSpanNum = form.spanNum;
  if (!volumeMembers.createRelated) {
    if (userInput) {
      // 清空物理盘选中项和容量
      volumeMembers.addCheckArr(volumeMembers.getCheckArr, volumePolicy.getTwoCache as boolean);
      volumeMembers.setCapacity = null;
      changeDriveDisable(false);
    }
  } else if (!form.spanNumDisabled && volumeMembers.createRelated && isPMCCard) {
    paramChanged();
  } else {}
  initForm();
  checkBtnState();
}
function setSpanValid(spanNum: any) {
  form.spanNum = spanNum.value;
  if (spanNum.disable) {
    form.spanNumDisabled = true;
  } else {
    form.spanNumDisabled = false;
  }
}

//创建maxCache逻辑盘时限制可设置的最大容量
function setMaxCacheCapacity(isInit: boolean = false) {
  let allowedMaxCapacity = 1.7 * 1024 * 1024 * 1024 * 1024;
  const currentCapacity = volumeMembers.getSelectData.capacityMBytes as number;
  const logicalMaxCapacity = Number(volumePolicy.getSelectData.associationLogical?.maxCapacity);
  if (volumePolicy.getSelectData.cacheLineSize?.id === '64K') {
    allowedMaxCapacity = 1.7 * 1024 * 1024 * 1024 * 1024;
  } else if (volumePolicy.getSelectData.cacheLineSize?.id === '256K') {
    allowedMaxCapacity = 6.8 * 1024 * 1024 * 1024 * 1024;
  }
  const maxCapacityMBytes = Math.min(allowedMaxCapacity, currentCapacity, logicalMaxCapacity);
  const result = computeCapacity(maxCapacityMBytes);
  let capacityInfo = null;
  if (isInit) {
    // 初始化时容量赋值有‘oldValue’属性表示容量值未变更，以便参数处理为null
    capacityInfo = {
      value: result.capacity,
      unit: result.unit,
      options: volumeMembers.getCapacity.options,
      batyValue: maxCapacityMBytes,
      oldValue: maxCapacityMBytes,
    };
  } else {
    capacityInfo = {
      value: result.capacity,
      unit: result.unit,
      options: volumeMembers.getCapacity.options,
      batyValue: maxCapacityMBytes,
    };
  }
  volumeMembers.setCapacityObj = capacityInfo;
}
</script>

<style scoped lang="scss">
:deep(.formVolumeName .el-form-item__content) {
  display: flex;
  align-items: center;
  font-size: 12px;
}
.el-input {
  width: 273px;
}
.el-select {
  width: 273px;
}
.formCapacity .el-input {
  width: 177px;
  margin-right: 8px;
}
.formCapacity .el-select {
  width: 88px;
}
.formVolumeName .el-input {
  margin-right: 10px;
}
.redStar {
  color: var(--o-color-danger);
}
.creat-drawer-box {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 100%;
}
:deep(.el-form-item.is-required .el-form-item__label) {
  position: relative;
}
:deep(.el-form-item.is-required .el-form-item__label::before) {
  position: absolute;
  left: -6px;
}
</style>

<style lang="scss" scoped>
.creat-drawer-box {
  .el-form {
    padding: 16px 24px 48px 24px;

    :deep(.text-el-form-item) {
      height: 16px;
      .el-form-item__label {
        padding-top: 0;
        padding-bottom: 0;
        &::before {
          top: 0px !important;
        }
      }

      .el-form-item__content {
        line-height: 16px;
      }
    }
  }

  .footer {
    position: fixed;
    bottom: 0;
    right: 0;
    z-index: 999999;
    width: 552px;
    background-color: var(--o-bg-color-base) !important;
    padding: 8px 24px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2);
  }
}
:deep(#twoCache) {
  .el-checkbox__input {
    .el-checkbox__inner {
      border-radius: 50%;
    }
    &.is-checked {
      .el-checkbox__inner {
        background-color: transparent;
        position: relative;
        &::after {
          width: 8px;
          height: 8px;
          border: none;
          outline: none;
          background-color: var(--o-checkbox-border-color_checked);
          border-radius: 50%;
          position: absolute;
          margin: auto;
          top: 0;
          left: 0;
          bottom: 0;
          right: 0;
        }
      }
    }
  }
}
:deep(.is-disabled .el-input__suffix) {
  display: inline-flex;
}
.required-form-item {
  position: relative;
  &::after {
    content: '*';
    position: absolute;
    left: -6px;
    top: 10px;
    color: var(--o-color-danger);
  }
}
.text-el-form-item {
  &::after {
    top: 2px;
  }
}
</style>
